const express = require('express');
const axios = require('axios');
const router = express.Router();
const pool = require('../db');

// 临时code 换openId
router.post('/getOpenId', async (req, res) => {
  try {
    const { code } = req.body;
    const appId = process.env.APP_ID;
    const appSecret = process.env.APP_SECRET;
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`;
    const response = await axios.get(url);
    const data = response.data;
    console.log(data)
    // 查询数据库是否新用户
    const query = 'SELECT * FROM sys_user WHERE openid = ?';
    const values = [data.openid];
     
    pool.query(query, values, async (error, results) => {
      console.log('用户表查询接口', results)
      if (error) {
        return res.status(500).json({ message: error.message });
      }
      
      if (results.length === 0) {
        data.status = 0
        console.log('我来插入新用户了')
        const insert = 'INSERT INTO sys_user (openid, createTime) VALUES (?,?)';
        await pool.query(insert, [data.openid, new Date()]);
      }
      res.json({
        success: true,
        code: 200,
        data: data,
        errMsg: '成功'
      });
    })
  } catch (error) {
    res.status(500).send()
  }
})

module.exports = router;